import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import store from '@/store'
import { apiUrl } from '@/config'
import { SYS_FLAG } from '@/store/constant'

export default () => {
  // axios
  axios.defaults.baseURL = apiUrl
  axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
  axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
  axios.defaults.paramsSerializer = (params) => {
    return qs.stringify(params, {
      indices: false
    })
  }

  // Request
  axios.interceptors.request.use(config => {
    // Set Authorization
    let auth = localStorage.getItem(SYS_FLAG.AUTH)
    if (auth) {
      config.headers.common['Authorization'] = auth
    }
    return config
  }, error => {
    return Promise.reject(error)
  })

  // Response
  axios.interceptors.response.use(response => {
    response.body = response.data
    let path = router.currentRoute.path
    let { isLogin, isNotLoginLocations } = Vue.prototype.$apiHelper
    let notLogin = !isLogin(response.body.responseCode)

    // 如果没有登录 - 跳转登录页面，并删除错误缓存信息
    if (notLogin && isNotLoginLocations(path)) {
      // 如果token存在
      let auth = localStorage.getItem(SYS_FLAG.AUTH)
      if (auth) {
        Vue.prototype.$Modal.error({
          title: '登录信息错误',
          content: '登录信息已过期，请重新登录',
          onOk: () => {
            localStorage.removeItem(SYS_FLAG.AUTH)
            store.commit('ACCOUNT_NOLOGIN')
            router.push({ path: '/login' })
          }
        })
      } else {
        localStorage.removeItem(SYS_FLAG.AUTH)
        store.commit('ACCOUNT_NOLOGIN')
      }
      return false
    }
    return response
  }, error => {
    return Promise.reject(error)
  })

  // Reset Post
  Vue.http = {
    get (url, data = {}) {
      return axios.get(url, {params: data})
    },
    post (url, data = {}) {
      data.token = localStorage.getItem(SYS_FLAG.AUTH)

      // 默认添加 cacheBuster 时间戳
      if (url.indexOf('?') > -1) {
        url += '&'
      } else {
        url += '?'
      }
      url += `cacheBuster=${Date.now()}`
      return axios.post(url, {
        requestData: data
      })
    }
  }
}
